package com.fire.web.modules.all.utils;

import com.fire.web.modules.all.constant.FastdfsConst;
import com.github.tobato.fastdfs.FdfsClientConfig;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.DefaultGenerateStorageClient;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Aspire
 */
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@Component
public class FastDFSClientWrapper {

	@Autowired
	private FastFileStorageClient storageClient;

	/** 日志 */
	protected static Logger LOGGER = LoggerFactory.getLogger(DefaultGenerateStorageClient.class);

	/**
	 * 上传文件
	 *
	 * @param file 文件对象
	 * @return 文件访问地址
	 * @throws IOException
	 */
	public String uploadFile(MultipartFile file) throws IOException {
		StorePath storePath = storageClient.uploadFile((InputStream) file.getInputStream(), file.getSize(),
				FilenameUtils.getExtension(file.getOriginalFilename()), null);
		return getResAccessUrl(storePath);
		//return storePath.getFullPath();
	}

	/**
	 * 删除文件
	 *
	 * @param fileUrl 文件访问地址
	 * @return 0-成功    1-失败
	 */
	public String deleteFile(String fileUrl) {
		if (StringUtils.isEmpty(fileUrl)) {
			return FastdfsConst.FAIL;
		}
		try {
			StorePath storePath = StorePath.praseFromUrl(fileUrl);
			storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
		} catch (Exception e) {
			LOGGER.warn(e.getMessage());
			return FastdfsConst.FAIL;
		}
		return FastdfsConst.SUCCESS;
	}

	// 封装文件完整URL地址
	private String getResAccessUrl(StorePath storePath) {
		String fileUrl = FastdfsConst.HTTP_SERVER_ADRESS + storePath.getFullPath();
		return fileUrl;
	}
}
